//
//  UITextField+Extension.swift
//  learnSwift
//
//  Created by mac on 2018/7/6.
//  Copyright © 2018年 hymiao. All rights reserved.
//

import UIKit
import RxSwift

private let disposeBag = DisposeBag()

private var key: Void?
extension UITextField: UITextFieldDelegate {
    
    /// 文字长度限制，默认为 Int.max
    public var textMaxLength: Int {
        get {
            return objc_getAssociatedObject(self, &key) as? Int ?? Int.max
        }
        set {
            objc_setAssociatedObject(self, &key, newValue, .OBJC_ASSOCIATION_COPY_NONATOMIC)
            
            self.rx.text.orEmpty.changed
                .subscribe(onNext:{ text in
                    
                    /// 限制输入长度
                    /// 只有设置了限制输入长度，才会执行限制流程
                    guard newValue != Int.max else {
                        return
                    }
                    
                    let toBeString = text as NSString
                    
                    let languate = UIApplication.shared.textInputMode?.primaryLanguage
                    if languate == "zh-Hans" {
                        let selectedRange = self.markedTextRange
                        
                        if let start = selectedRange?.start {
                            // 获取高亮部分
                            if self.position(from: start, offset: 0) != nil {
                                // 有高亮选择的字符串，则暂不对文字进行统计和限制
                                return
                            }
                        }
                    }
                    
                    if toBeString.length > self.textMaxLength {
                        self.text = toBeString.substring(to: self.textMaxLength)
                    }
                    
                })
                .disposed(by: disposeBag)
        }
    }
}


